<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <!-- 顶部按钮 -->
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermission(1,'0')">添加权限</el-button>
        </div>

        <!-- 表格区域 -->
        <!-- 当 row 中包含 children 字段时，被视为树形数据。渲染树形数据时，必须要指定 row-key -->
        <el-table border :data="permissionList" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <!-- type为1时，为页面访问权限，显示添加按钮 -->
              <!-- type为2时，为按钮访问权限，部不加按钮 -->
              <el-button v-if="scope.row.type === 1" type="text" @click="addPermission(2,scope.row.id)">添加</el-button>
              <el-button type="text" @click="editPermission(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="deletPermission(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 新增权限的弹框 -->
        <el-dialog ref="addPermission" :title="isEdit? '编辑权限':'新增权限'" :visible="showDialog" @close="btnCancel">
          <!-- 表单 -->
          <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width:90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="permissionSubmit">确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getPermissionListAPI, addPermissionAPI, getPermissionDetailAPI, editPermissionAPI, deletPermissionAPI } from '@/api/permission'
import { getTreeData } from '@/utils/getTreeData'
export default {
  name: 'Permission',
  data() {
    // 验证权限名称(同级不能出现相同的名称)
    const validName = (rule, value, callback) => {
      // 找到同级兄弟节点权限,将所有兄弟节点name组成一个数组
      let existList = this.originList.filter(item => item.pid === this.formData.pid).map(item => item.name.trim())
      // 如果是编辑状态，则要排除当前的权限名称
      if (this.isEdit) {
        existList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id).map(item => item.name.trim())
      }
      // 判断当前名称是否在上述数组中
      existList.includes(value) ? callback(new Error('此权限名称已存在')) : callback()
    }
    // 验证权限标识(项目中的 权限标识 是唯一的)
    const validCode = (rule, value, callback) => {
      // 找到同级兄弟节点权限,将所有兄弟节点name组成一个数组
      let existList = this.originList.map(item => item.code)
      // 如果是编辑状态，需要将当前权限标识排除在外
      if (this.isEdit) {
        existList = this.originList.filter(item => item.code !== this.formData.code).map(item => item.code)
      }
      // 判断当前名称是否在上述数组中
      existList.includes(value) ? callback(new Error('此权限标识已存在')) : callback()
    }
    return {
      permissionList: [],
      showDialog: false,
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }]
      },
      isEdit: false,
      originList: [] // 精简后数据，用于特殊校验
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 删除权限
    async deletPermission(id) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes === 'cancel') return this.$message('取消删除')
      const res = await deletPermissionAPI(id)
      // console.log(res)
      this.$message.success(res.message)
      this.getPermissionList()
    },

    // 添加权限的方法
    async addPermissionFn() {
      const res = await addPermissionAPI(this.formData)
      // console.log(res)
      this.$message.success(res.message)
    },

    // 编辑权限的方法
    async editPermissionFn() {
      const res = await editPermissionAPI(this.formData)
      console.log(res)
      this.$message.success(res.message)
    },

    // 点击编辑，弹框显示,获取权限详情，数据回填
    async editPermission(id) {
      this.isEdit = true
      const res = await getPermissionDetailAPI(id)
      console.log(res)
      this.formData = res.data
      this.showDialog = true
    },

    // 点击确定，添加或修改权限
    permissionSubmit() {
      this.$refs.perForm.validate(async valid => {
        if (!valid) return false
        this.isEdit ? this.editPermissionFn() : this.addPermissionFn()
        this.showDialog = false
        this.getPermissionList()
      })
    },

    // 点击新增权限，显示弹框 (将权限类型type和父节点的pid传入)
    addPermission(type, pid) {
      this.isEdit = false
      this.showDialog = true
      // 获取当前的权限类型和父级pid
      this.formData.type = type
      this.formData.pid = pid
    },

    // 点击取消或关闭弹框，清空表单数据，重置表单规则
    btnCancel() {
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      this.$refs.perForm.resetFields()
      this.showDialog = false
    },

    // 获取所有权限
    async getPermissionList() {
      const res = await getPermissionListAPI()
      // console.log(res)
      this.permissionList = getTreeData(res.data)
      // 精简数据
      this.originList = res.data.map(item => ({
        id: item.id,
        code: item.code,
        pid: item.pid,
        name: item.name
      }))
    }
  }
}
</script>

<style lang="scss" scoped></style>
